# -*- coding: utf-8 -*-
"""
@File:   crypto.py
@Author: jk.dong
@Desc:   加密、解密模块
"""
import base64
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad


def check(value: list, length: list):
    if len(value) not in length:
        raise ValueError("密钥长度不符合要求")
    return bytes(value)


class PrpCrypt:
    def __init__(self, key: list, vector: list):
        # 密钥 16、24或32字节
        self.key = check(key, [16, 24, 32])
        # 初始化向量 16字节
        self.iv = check(vector, [16])
        self.mode = AES.MODE_CBC

    # 加密
    def encrpyt(self, text):
        text_pad = pad(text.encode('utf-8'), AES.block_size)  # 填充后的字节串
        crpytor = AES.new(self.key, self.mode, self.iv)  # 生成算法对象
        encrypt_data = crpytor.encrypt(text_pad)
        return base64.b64encode(encrypt_data).decode()

    # 解密
    def decrypt(self, text):
        data = base64.b64decode(text.encode())
        crpytor = AES.new(self.key, self.mode, self.iv)
        decrypt_data = crpytor.decrypt(data)
        res = unpad(decrypt_data, AES.block_size).decode()  # 去除多余字符
        return res


def decrypt(pwd: str, config_: dict) -> str:
    secret = PrpCrypt(config_.get('secret_key'),
                      config_.get('secret_vector'))
    return secret.decrypt(pwd)
